<?php 
require_once("../config/config.php");
session_name("miushake");
session_start();
if (!isset($_COOKIE['miushake_autoplay']))
	Outils_Cookie::setCookieLive("miushake_autoplay","true");
if (!isset($_COOKIE['miushake_containerevalvisible']))
	Outils_Cookie::setCookieLive("miushake_containerevalvisible","false");
// Initialisation des variables
$titre = "";
$c = "";
$connectInscriptForm = "";
$mainSearchInput = Recherche::searchForm("cleMainSearch","","maRecherche");
$squelette = "../ui/pages/squelette.html";


// Test s'il s'agit d'une requête Ajax
$ajax = false;

if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
  	$ajax = true;
}

try {
		
	
	 // AUTHENTIFICATION

	 //Création d'un singleton Auth
	$auth = Auth::getInstance();
	 //Initialisation de l'interface graphique 
	$authUi = new Auth_Ui($auth);
	
	// Par défaut, $authUi doit afficher le formulaire de connexion et le menu par defaut
	$usernav = $authUi->afficherUsernavDefaut();
	
	if (isset($_POST['mail']) && isset($_POST['passwd'])) {
	    $repconnex = $auth->verifierAuthentification($_POST['mail'], $_POST['passwd']);
		if ($ajax){
			switch($repconnex){
				case CNX_OK:	
					echo "<span id=\"response\">ok</span>";
					break;
				case ERREUR_MDP_LOGIN:	
					echo "<span id=\"response\">E-mail ou mot de passe incorrect.</span>";
					break;
				case ERREUR_CPTE_DSCT:
					echo "<span id=\"response\">Votre compte est désactivé</span>";
					break;
				default:
					break;
			}
		}
  	}
	
	if ($auth->estConnecte()) {
    	$usernav = trim($authUi->afficherUsernav());
		$nNotifs = Notification_Bd::count("id_user_object={$auth->getInfosAuthentification()->getIdUser()} AND state=".NOTIFICATION_NEW);
		if ($ajax && isset($_POST['mail'])){
			$usernav = addslashes($usernav);
			echo "<script type=\"text/javascript\">$('wrapper').getElement('header').getElement('nav').getElement('ul').set('html','{$usernav}');addEventPage();notificationNbInstance = new NotificationNb({$nNotifs});$('recommandationui').fireEvent('connected');</script>";
		} else {
			$usernav .=	"<script type=\"text/javascript\">window.addEvent('domready',function(){\$('recommandationui').fireEvent('connected');notificationNbInstance = new NotificationNb({$nNotifs})});</script>";
		}
		//var_dump($auth->getInfosAuthentification()->getIdUtilisateur());
		// redirection s'il s'agit d'un admin ou d'un modo
		/*if ($_SESSION['infosAuth']->getTypeUtilisateur() == "membre"){
			$script=Auth_Control::redirection(MEMBRE_URL . "index.php");
		}
		if ($_SESSION['infosAuth']->getTypeUtilisateur() == "adm") {
			$script=Auth_Control::redirection(ADMIN_URL . "index.php");
		}*/	
  	} else {
		$inscriptForm = new User_Form(new User(array()));
		$authForm = new Auth_Form($auth);
		$connectInscriptForm = $authForm->makeConnectionForm("index.php").$inscriptForm->makeInscriptForm("index.php?a=inscription");
	}
	
	$action = isset($_GET['a']) ? $_GET['a'] : "";
	
	$data = is_array($_POST) ? $_POST : array();
	
  	Outils_Chaines::htmlEncodeArray($data);
	
	// $recherche = Recherche::initialize(is_array($_GET) ? $_GET : array());
	//$recherchebar = $recherche->rechercheFormMini("index.php?a=rechercher","Rechercher");


// controleur
 	switch($action) {
		
		/* Recherche */
		
		case "autoCompleteSearch":
			$search = isset($data['cle']) ? $data['cle'] : ""; 
			$title = isset($data['title']) && $data['title'] ? true : false;
			$user = isset($data['user']) && $data['user'] ? true : false;
			if (is_string($search) && strlen($search) > 2 && strlen($search) < 64) {
				if ($title){
					$rechercheT = new Recherche($data,"Title");
					$rechercheT->setAutoComplete(true);
					$limitT = "LIMIT 0,10";
					$clauseT = $rechercheT->makeTabClause($limitT);
					$resultTTab = Title_Bd::getTitlesFromSearch($clauseT);
					foreach($resultTTab as $title){
						echo "<li><span class=\"titleL\"><div style=\"display:inline\">{$title->getArtist()} {$title->getName()}</div><input type=\"hidden\" class=\"idTitle\" value=\"{$title->getIdTitle()}\"/></span><span class=\"autocompleteroverflow music\"></span></li>";
					}
				}
				if ($user){
					$rechercheU = new Recherche($data,"User");
					if ($auth->estConnecte())
						$limitU = "AND id_user!={$auth->getInfosAuthentification()->getIdUser()} LIMIT 0,4";
					else 
						$limitU = "LIMIT 0,4";
					$clauseU = $rechercheU->makeTabClause($limitU);
					$resultUTab = User_Bd::getUsersFromSearch($clauseU);
					foreach($resultUTab as $user){
						echo "<li><span class=\"userL\"><div style=\"display:inline\">{$user->getName()}</span></div><input type=\"hidden\" class=\"idUser\" value=\"{$user->getIdUser()}\"/><span class=\"autocompleteroverflow user\"></span></li>";
					}
				}
			}
			break;
		
		case "rechercher":
			$search = isset($_GET['cle']) ? $data['cle'] = $_GET['cle'] : "";
			$title = isset($_GET['title']) && $_GET['title'] ? true : false;
			$user = isset($_GET['user']) && $_GET['user'] ? true : false;
			$yt = isset($_GET['yt']) && $_GET['yt'] ? true : false;
			
			$blocRequest = false;
			
			// Test des blocTarget
			if (isset($_GET['typeP']) && $_GET['typeP']=='bloc'){
				$blocRequest = true;
				if (isset($_GET['blocTarget'])){
					$title=false;
					$user = false;
					$yt = false;
					switch($_GET['blocTarget']){						
						case "blocResultYT":
							$yt = true;
							break;
						case "blocResultTitles":
							$title = true;
							break;
						default:
							$user = true;
							break;
					}
				}
			}

			if (is_string($search) && strlen($search) > 0 && strlen($search) < 64) {
				$html = "";
				if ($title && $user){
					$html .= "<h1>ma recherche</h1>";
				}
				if ($title){
					$rechercheT = new Recherche($data,"Title");
					$clauseT = $rechercheT->makeTabClause();				
					$listeT = new Liste_Paginee("Title_Bd", "getTitlesFromSearch", $clauseT);
					$listeTUi = new Liste_Paginee_Ui($listeT,10,7,true);
					$nbResultT = $listeT->count();
					$resultT = $nbResultT > 0 ? $listeTUi->makeHtml("Title_Ui", "getTitleForList",array(false,true,true,true,true)) : "<p class=\"resultS\">Aucun résultat.</p>"; 
					if ($blocRequest){
							echo $resultT;
							break;
					} else {
						$html .= "<section><h1>Résultat de la recherche de titres</h1><div id=\"blocResultTitles\" class=\"containerBlocP\">{$resultT}</div></section>";
					}
					// Pertinance
					if ($nbResultT > 0){
						$firstTitle = Title_Bd::getRelevance($clauseT," LIMIT 1");
						$maxRelevance = Title_Bd::getRelevance("MATCH(name,artist) AGAINST(\"".$firstTitle['name']." ".$firstTitle['artist']."\")","AND id_title=".$firstTitle['id_title']);
						$relevanceSearch = Title_Bd::getRelevance("MATCH(name,artist) AGAINST(\"".$search."\")");
						$pertinance = $relevanceSearch['relevance']*100/$maxRelevance['relevance'];
						if ($pertinance > RELEVANCE_SEARCH)
							$yt = false;
					}
				}
				if ($yt){
					$html .= "<section><h1>Résultat de la recherche YT</h1><div id=\"blocResultYT\" class=\"containerBlocP\">";
					//var_dump(urlencode($search));
					$ytApi = YTGdataApi::getInstance(YOUTUBE_API_KEY);
					try {
						if ($blocRequest){
							$ytApi->setStartIndex($_GET['p']);
							echo $ytApi->getYtVideos($search);
							break;
						} else{
							$html .= $ytApi->getYtVideos($search);
						}
					} catch (Exception $e) {
						$html .= $e->getMessage();	
					}
					$html.= "</div></section>";

				}
				if ($user){
					$rechercheU = new Recherche($data,"User");
					$txtTitre = isset($_GET['title']) ? ""  : "<p class=\"resultS resultT\">Résultat de la recherche</p>";
					
					if ($auth->estConnecte())
						$limitU = "AND id_user!={$auth->getInfosAuthentification()->getIdUser()}";
					else 
						$limitU = "";
					$clauseU = $rechercheU->makeTabClause($limitU);
					$listeU = new Liste_Paginee("User_Bd", "getUsersFromSearch", $clauseU);
    				$listeUi = new Liste_Paginee_Ui($listeU,5,7,true);
					$resultU =  $listeU->count() > 0 ? $txtTitre.$listeUi->makeHtml("User_Ui", "getUserCard") : "<p class=\"resultS\">Aucun résultat.</p>";
					$resultU .= "<script type=\"text/javascript\">addEventInteracUser();initializeVennTips();</script>"; 
					if ($blocRequest|| !$title && !$yt ){
						echo $resultU;
						break;
					} else {
						$html .= "<section><h1>Résultat de la recherche des utilisateurs</h1><div id=\"blocResultUsers\" class=\"containerBlocP\">{$resultU}</div></section>";
					}
				}
				echo $html;
			}
			break;
		
		/* Recommandation next() */
		case "next":
			//$recommendation = Recommendation::initialize(RECOMMANDATION_ALEATOIRE); 
			//$recommendation = Recommendation::initialize(RECOMMANDATION_POPULAIRE); 
			//$recommendation = Recommendation::initalizeRandom();
			$title = new Title();
			while ($title->getIdTitle() == null){
				$recommendation = Recommendation::initalizeRandom();
				$title = $recommendation->next();
			}
			$name = Outils_Chaines::htmlEncodeString($title->getName());
			$artist = Outils_Chaines::htmlEncodeString($title->getArtist());
			header('Content-Type: text/xml; charset=utf-8');
			echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?><title><youtube_id>{$title->getYoutubeId()}</youtube_id><name>{$name}</name><artist>{$artist}</artist><id_title>{$title->getIdTitle()}</id_title><method_recommendation>{$recommendation->getMethodRecommendation()}</method_recommendation></title>";
		/*	echo "<youtube_id>{$title->getYoutubeId()}</youtube_id><name>{$title->getName()}</name><artist>{$title->getArtist()}</artist><id_title>{$title->getIdTitle()}</id_title>";*/
			break;
			
		/* Une vidéo selectionné */
		
		case "getVideoById":
			$title = Title_Bd::getTitle($_GET['id_title']);
			$name = Outils_Chaines::htmlEncodeString($title->getName());
			$artist = Outils_Chaines::htmlEncodeString($title->getArtist());
			$recommendation = RECOMMANDATION_CHOIX_UTILISATEUR;
			header('Content-Type: text/xml; charset=utf-8');
			echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?><title><youtube_id>{$title->getYoutubeId()}</youtube_id><name>{$name}</name><artist>{$artist}</artist><id_title>{$title->getIdTitle()}</id_title><method_recommendation>{$recommendation}</method_recommendation></title>";			
			break;
			
		/*  rafraichissement de l'interface de recommandation RecommandUi (lors d'un changement d'un appel à next)*/
		case "refreshRecommandUi":
			if ($auth->estConnecte()){
				$rating = Rating_Bd::getRating($auth->getInfosAuthentification()->getIdUser(),$data['id_title']);
				$rating->update($data);
				if ($data['id_title']!= -1){
					if ($rating->getIdRating() == null)
						$rating = Rating_Bd::addRating($rating);
				}
				else {// id_title= -1 -> vidéo YT  
					$rating->setIdRating(-1);
				}
				header('Content-Type: text/xml; charset=utf-8');
				echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?><rating><id_rating>{$rating->getIdRating()}</id_rating><score>{$rating->getScore()}</score><time>{$rating->getTime()}</time><id_title>{$rating->getIdTitle()}</id_title></rating>";
			}
			break;
			
		/* Mise à jour de l'évaluation */
		case "updateEval":
			if ($auth->estConnecte() && $ajax){
				if ($data['id_rating']!=-1){
					$rating = Rating_Bd::getRatingById($data['id_rating']);
					$rating->update($data);
					Rating_Bd::modifyRating($rating);
				} else { // rating -1 -> vidéo YT donc enregistrement de Title avant évaluation
					if (isset($data['artist']))
						$data['artist'] = html_entity_decode ( $data['artist']);
					if (isset($data['name']))
						$data['name'] = html_entity_decode ( $data['name']);
					$title=new Title($data);
					$chktitle = Title_Bd::checkIfVideo($title->getYoutubeId());
					if ( $chktitle === false ){
						$title=Title_Bd::addTitle($title);
						$data['id_title'] = $title->getIdTitle();
						$rating = new Rating();
						$rating->update($data);
						$rating = Rating_Bd::addRating($rating);
						echo "<script type=\"text/javascript\">returnedIdTitle={$title->getIdTitle()};returnedIdRating={$rating->getIdRating()};</script>";
					}
				}
			}
			break;
		
		/* Déconnexion */	
		case "quitter":
			$auth->quitter();
			$usernav = trim($authUi->afficherUsernavDefaut());
			$inscriptForm = new User_Form(new User(array()));
			$authForm = new Auth_Form($auth);
			$connectInscriptForm = $authForm->makeConnectionForm("index.php").$inscriptForm->makeInscriptForm("index.php?a=inscription");
			if ($ajax){
				$usernav = addslashes($usernav);
				echo "<script type=\"text/javascript\">$('userbar').set('html','${usernav}');$('recommandationui').fireEvent('disconnected');</script>{$connectInscriptForm}";
			}
			break;
			
		/* Inscription */
		case "inscription":
			if ($ajax){
				$user = new User($data);
				$userForm = new User_Form($user);
				if ($userForm->checkInscript($data)){
					User_Bd::addUser($user);
					$auth->verifierAuthentification($user->getMail(), $user->getPassword());

					echo "<span id=\"response\">ok</span>";
					if ($auth->estConnecte())
						$usernav = trim($authUi->afficherUsernav());
						$usernav = addslashes($usernav);
						$nNotifs = Notification_Bd::count("id_user_object={$auth->getInfosAuthentification()->getIdUser()} AND state=".NOTIFICATION_NEW);
						echo "<script type=\"text/javascript\">$('wrapper').getElement('header').getElement('nav').getElement('ul').set('html','{$usernav}');addEventPage();notificationNbInstance = new NotificationNb({$nNotifs});$('recommandationui').fireEvent('connected');</script>";
				}
				else
					echo $userForm->makeInscriptForm("index.php?a=inscription");
			}
			break;
			
		/* Navigation entre les pages */

		case "getPage":
			if (isset($_GET['page'])){
				$page = $_GET['page'];
				$html = "";
				switch($page){
					
					case "accueil":
						$Tabtop5titles = Title_Bd::getTop5(5);
						$top5title = "";
						foreach ($Tabtop5titles as $t){
							$t_Ui = new Title_Ui($t);
							$top5title .= $t_Ui->getTitleForList();	
						}
						$tabtop5user = User_Bd::topEvaluateur(5);
						$top5user = "";
						foreach ($tabtop5user as $u){
							$u_Ui = new User_Ui($u);
							$top5user .= $u_Ui->getMiniUserCardFriend();	
						}
						$Tablast5 = Title_Bd::getTitlesFromSearch("1=1 ORDER BY id_title DESC LIMIT 5");
						$last5title = "";
						foreach ($Tablast5 as $t){
							$t_Ui = new Title_Ui($t);
							$last5title .= $t_Ui->getTitleForList();	
						}
						$totalTitres = Title_Bd::count();
						$html = <<<EOT
							<section id="presentation">
								<div class="illAccueil">
								<a href="#" class="goToShakeIt">Commencez l'expérience <br /> dès maintenant!</a><!-- ' -->
								<p>{$totalTitres} titres<br /> <span>(pour l'instant!)</span> <!-- '--></p>
								</div>
							</section>
							<section id="topmiushake">
								<div id="leftside">
								<section class="sidebloc">
									<h2>Les 5 <span>derniers titres</span> ajoutés</h2>
									<div>
									{$last5title}
									</div>
								</section>
								<section class="sidebloc">
									<h2>Top 5 des <span>évaluateurs</span></h2>
									<div>
									{$top5user}
									</div>
								</section>
								<section class="sidebloc">
									<h2>Top 5 des <span>titres populaires</span></h2>
									<div>
									{$top5title}
									</div>
								</section>
								<div class="clearer"></div>
								</div>
							</div>
EOT;

						$html .= "<script type=\"text/javascript\">addEventInteracUser();addEventTitle($('topmiushake'));$$('.goToShakeIt').addEvent('click',function(ev){ev.stop(); HM.set('page','shakeIt');});</script>";
						break;
					
					case "maContribution":
						if (! $auth->estConnecte())
							break;
						$user = User_Bd::getUser($auth->getInfosAuthentification()->getIdUser());
						$userUi = new User_Ui($user);
						//$stats = $userUi->getUserStats();					
						$html = <<<EOT
							<div id="leftside">
								<nav class="sidebloc" id="contribmenu">
									<h2>Ma <span>contribution</span></h2>
									<div>
										<ul>
											<li><a class="navcat" id="messtats" href="#">mes stats</a></li>
											<li><a class="navcat" id="mesevals" href="#">mes évaluations</a></li>
											<li><a class="navcat" id="mesamis" href="#">mes amis</a></li>
											<li><a class="navcat" id="mawatchlist" href="#">ma &laquo;watch list&raquo;</a></li>
										</ul>
									</div>
								</nav>
								<section class="sidebloc updateOnEval needAuth updateOnAddFriend updateOnAddWatchList">
									<h2>En bref</h2>
									<div class="sideblocUpdateContainer enBref" id="getEnBref">
										<!--update auto par JS-->
									</div>
								</section>
							</div>
							<section id="principalcontent">
							</section>
							<div class="clearer"></div>
					
EOT;
						$html .= "<script type=\"text/javascript\">defaultcat=\"messtats\";</script>";

						break;
						
					case "monCompte":
						if (! $auth->estConnecte())
							break;
						$html = <<<EOT
							<div id="leftside">
								<nav class="sidebloc" id="comptemenu">
									<h2>Mon <span>compte</span></h2>
									<div>
										<ul>
											<li><a class="navcat" id="mesinfos" href="#">mes informations</a></li>
											<li><a class="navcat" id="mesprefs" href="#">mes préférences</a></li>
											<li><a class="navcat" id="mesnotifs" href="#">mes notifications</a></li>
										</ul>
									</div>
								</nav>
							</div>
							<section id="principalcontent">
							</section>
							<div class="clearer"></div>
					
EOT;
							$html .= "<script type=\"text/javascript\">defaultcat=\"mesinfos\";</script>";
						break;
						
					case "voirProfil":
						if (!$ajax || !isset($_GET['id_user']))
							break;
						$user = User_Bd::getUser($_GET['id_user']);	
						$userUi = new User_Ui($user);				
						// Clauses
						// Ses dernières évaluations
						$clauseLastEvals = "id_user={$user->getIdUser()} AND score>-1 ORDER BY time DESC";
						// Ses dernières meilleurs évaluations
						$clauseTopEval = "id_user={$user->getIdUser()} AND score>5 ORDER BY score DESC,time DESC";
						// Mes derniers morceaux les plus mal notés
						$clauseWorseEval = "id_user={$user->getIdUser()} AND score>-1 AND score <5 ORDER BY score ASC,time DESC";					
						// Gestion des bloc paginées
						if (isset($_GET['typeP']) && $_GET['typeP']=='bloc'){
							if (isset($_GET['blocTarget'])){
								$blocTarget = $_GET['blocTarget'];
								$clauseB = "";
								$tabParam = array();
								switch($blocTarget){
									case "blocLastEvals":
										$clauseB = $clauseLastEvals;
										$tabParam = array(true,true,true,true);
										break;
									case "blocTopEval":
										$clauseB = $clauseTopEval;
										$tabParam = array(true,false,true);
										break;
									case "blocWorseEval":
										$clauseB = $clauseWorseEval;	
										$tabParam = array(true,false,true);		
										break;
									default:
										throw new Exception("id Container bloc paginé inconnu");
										break;
								}
								$liste = new Liste_Paginee("Rating_Bd", "lireListe", $clauseB);
								$listeUi = new Liste_Paginee_Ui($liste,5,7,true); // dernier paramètre à true voulant dire qu'il s'agit des bloc de listes paginées
								echo $liste->count() > 0 ? $listeUi->makeHtml("Rating_Ui", "getRatingList",$tabParam) : "<p style=\"text-align:center\">Aucun résultat.</p>"; 									
								break;
							} else {
								throw new Exception("Param blocTarget manquant");	
							}
						}
						// Ses dernières évaluations
						$listeLastEvals = new Liste_Paginee("Rating_Bd", "lireListe", $clauseLastEvals);
    					$listeLastEvalsUi = new Liste_Paginee_Ui($listeLastEvals,5,7,true);
						$resultLastEvals = $listeLastEvals->count() > 0 ? $listeLastEvalsUi->makeHtml("Rating_Ui", "getRatingList",array(true,true,true,true)) : "<p class=\"resultS\">Aucun résultat.</p>"; 
						// Ses dernières meilleurs évaluations
						$listeTopEval = new Liste_Paginee("Rating_Bd", "lireListe", $clauseTopEval);
    					$listeTopEvalUi = new Liste_Paginee_Ui($listeTopEval,5,7,true);
						$resultTopEval = $listeTopEval->count() > 0 ? $listeTopEvalUi->makeHtml("Rating_Ui", "getRatingList",array(true,false,true)) : "<p class=\"resultS\">Aucun résultat.</p>"; 
						// Mes derniers morceaux les plus mal notés
						$listeUnrated = new Liste_Paginee("Rating_Bd", "lireListe", $clauseWorseEval);
    					$listeUnratedUi = new Liste_Paginee_Ui($listeUnrated,5,7,true);
						$resultWorseEval = $listeUnrated->count() > 0 ? $listeUnratedUi->makeHtml("Rating_Ui", "getRatingList",array(true,false,true)) : "<p class=\"resultS\">Aucun résultat.</p>"; 
						$evals= "<h1>ses évaluations</h1><section><h1>Ses dernières évaluations</h1><div id=\"blocLastEvals\" class=\"containerBlocP\">{$resultLastEvals}</div></section><section><h1>Ses dernières meilleurs évaluations</h1><div id=\"blocTopEval\"  class=\"containerBlocP\">{$resultTopEval}</div></section><section><h1>Ses dernieres mauvaises évaluations</h1><div id=\"blocWorseEval\" class=\"containerBlocP\">{$resultWorseEval}</div></section>";

						$html = <<<EOT
							<div id="leftside">
								<section class="sidebloc">
									<h2>Le profil de <span>{$user->getName()}</span></h2>
									<div>
										{$userUi->getProfilUserCard()}
									</div>
								</section>
								<section class="sidebloc">
									<h2>{$user->getName()} en <span>chiffres</span></h2>
									<div>
										{$userUi->getEnBref()}
									</div>
								</section>
								<section class="sidebloc needAuth">
									<h2><span>Affinité</span>Musicale</h2>
									<div class="sideblocUpdateContainer " id="getMusicalAffinity">
										<!--update auto par JS-->
										
									</div>
								</section>
								<section class="sidebloc needAuth">
									<h2>Vos <span>amis commun</span></h2>
									<div class="sideblocUpdateContainer containerBlocP" id="getCommonFriends">
										<!--update auto par JS-->
									</div>
								</section>
							</div>
							<section id="principalcontent">
								{$evals}
							</section>
							<div class="clearer"></div>
EOT;

						break;
						
					case "espaceAdmin":
						if (! $auth->estConnecte() || $auth->getInfosAuthentification()->getStatus() < MODO )
							break;
						$html = <<<EOT
							<div id="leftside">
								<nav class="sidebloc" id="adminmenu">
									<h2><span>Administration</span></h2>
									<div>
										<ul>
											<li><a class="navcat" id="utilisateurs" href="#">les utilisateurs</a></li>
											<li><a class="navcat" id="statsrecommand" href="#">les statistiques</a></li>
											<li><a class="navcat" id="maintenancetitle" href="#">la maintenance du contenu</a></li>
										</ul>
									</div>
								</nav>
							</div>
							<section id="principalcontent">
							</section>
							<div class="clearer"></div>
					
EOT;
							$html .= "<script type=\"text/javascript\">defaultcat=\"utilisateurs\";</script>";
						break;
						
					case "shakeIt":
						$html = <<<EOT
							<nav id="shakeItsubmenu">
								<ul>
									<li><a class="navcat needTitle" id="artisteinfos" href="#">l'artiste</a></li><!-- ' -->
									<li><a class="navcat needTitle" id="parolesinfos" href="#">paroles</a></li>
									<li><a class="navcat needTitle" id="evenementsinfos" href="#">evenements</a></li>
									<li><a class="navcat needTitle" id="acheterinfos" href="#">acheter</a></li>
									<li><a class="navcat needTitle" id="commentairesinfos" href="#">commentaires</a></li>
								</ul>
								<div class="clearer"></div>
							</nav>
							<div id="leftside">
								<section class="sidebloc updateOnNext needAuth">
									<h2>Vos <span>amis</span> l'ont noté !</h2><!--'-->
									<div class="sideblocUpdateContainer containerBlocP" id="getFriendsEvals">
										<!--update auto par JS-->
									</div>
								</section>
								<section class="sidebloc updateOnNext updateOnEval">
									<h2>Avis des <span>utilisateurs</span></h2>
									<div class="sideblocUpdateContainer" id="getEvalByTitle">
										<!--update auto par JS-->
									</div>
								</section>
								<section class="sidebloc updateOnNext updateOnEval needAuth">
									<h2>Vos dernières <span>évaluations</span></h2>
									<div class="sideblocUpdateContainer" id="getLastEvals">
										<!--update auto par JS-->
									</div>
								</section>
							</div>
							<section id="principalcontent">
							</section>
							<div class="clearer"></div>					
EOT;
							$html .= "<script type=\"text/javascript\">defaultcat=\"artisteinfos\";</script>";

						break;
						
					case "maRecherche":
						$html = <<<EOT
							<div id="leftside">
								<section class="sidebloc">
									<h2>Aide</h2>
									<div class="aideRecherche">
										<p>Votre recherche est tout d'abord analysé au sein de Miushake afin de vous sortir le résultat le plus pertinant possible. Si votre recherche ne donne aucun résultat ou si la pertinance de cette dernière n'est pas asser convaincante, une liste de vidéos Youtube vous sera proposée.</p> <p>Il est conseillé de formuler la requête de recherche en étant le plus complet et le plus précis possible.</p>
									</div>
								</section>
							</div>
							<section id="principalcontent" class="searchResultContainer">
								
							</section>
							<div class="clearer"></div>
					
EOT;
							$html .= "<script type=\"text/javascript\">window.fireEvent('maRecherchePageloaded');</script>";
					
						break;
							
					default:
						$html = "<p>Partie non implémentée</p>";
						break;	
				}
				echo $html;
			}
			break;
			
		/* Changement de sous catégories d'une page */
		case "getCat":
			if (isset($_GET['cat'])){
				$page = $_GET['cat'];
				$html = "";
				
				switch($page){
					
					case "messtats":
						if (! $auth->estConnecte())
							break;
						//$user = User_Bd::getUser($auth->getInfosAuthentification()->getIdUser());
						$user = $auth->getInfosAuthentification();
						$userUi = new User_Ui($user);
						$stats = $userUi->getUserStats();					
						$html = "<h1>mes stats</h1>{$stats}";
						break;
					
					case "mesevals":
						if (! $auth->estConnecte())
							break;
						//$user = User_Bd::getUser($auth->getInfosAuthentification()->getIdUser());
						$user = $auth->getInfosAuthentification();
						// Clauses
						// Mes dernières évaluations
						$clauseLastEvals = "id_user={$user->getIdUser()} AND score>-1 ORDER BY time DESC";
						// Mes dernières meilleurs évaluations
						$clauseTopEval = "id_user={$user->getIdUser()} AND score>5 ORDER BY score DESC,time DESC";
						// Mes derniers morceaux non notés
						$clauseUnrated = "id_user={$user->getIdUser()} AND score=-1 ORDER BY time DESC";
						
						// Gestion des bloc paginées
						if (isset($_GET['typeP']) && $_GET['typeP']=='bloc'){
							if (isset($_GET['blocTarget'])){
								$blocTarget = $_GET['blocTarget'];
								$clauseB = "";
								$tabParam = array();
								switch($blocTarget){
									case "blocLastEvals":
										$clauseB = $clauseLastEvals;
										$tabParam = array(true,true,true,true);
										break;
									case "blocTopEval":
										$clauseB = $clauseTopEval;
										$tabParam = array(true,false,true);
										break;
									case "blocUnrated":
										$clauseB = $clauseUnrated;	
										$tabParam = array(false,false,true);		
										break;
									default:
										throw new Exception("id Container bloc paginé inconnu");
										break;
								}
								$liste = new Liste_Paginee("Rating_Bd", "lireListe", $clauseB);
								$listeUi = new Liste_Paginee_Ui($liste,5,7,true); // dernier paramètre à true voulant dire qu'il s'agit des bloc de listes paginées
								$html = $liste->count() > 0 ? $listeUi->makeHtml("Rating_Ui", "getRatingList",$tabParam) : "<p style=\"text-align:center\">Aucun résultat.</p>"; 
							} else {
								throw new Exception("Param blocTarget manquant");	
							}
						} else {
						// Mes dernières évaluations
						$listeLastEvals = new Liste_Paginee("Rating_Bd", "lireListe", $clauseLastEvals);
    					$listeLastEvalsUi = new Liste_Paginee_Ui($listeLastEvals,5,7,true);
						$resultLastEvals = $listeLastEvals->count() > 0 ? $listeLastEvalsUi->makeHtml("Rating_Ui", "getRatingList",array(true,true,true,true)) : "<p class=\"resultS\">Aucun résultat.</p>"; 
						// Mes dernières meilleurs évaluations
						$listeTopEval = new Liste_Paginee("Rating_Bd", "lireListe", $clauseTopEval);
    					$listeTopEvalUi = new Liste_Paginee_Ui($listeTopEval,5,7,true);
						$resultTopEval = $listeTopEval->count() > 0 ? $listeTopEvalUi->makeHtml("Rating_Ui", "getRatingList",array(true,false,true)) : "<p class=\"resultS\">Aucun résultat.</p>"; 
						// Mes derniers morceaux non notés
						$listeUnrated = new Liste_Paginee("Rating_Bd", "lireListe", $clauseUnrated);
    					$listeUnratedUi = new Liste_Paginee_Ui($listeUnrated,5,7,true);
						$resultUnrated = $listeUnrated->count() > 0 ? $listeUnratedUi->makeHtml("Rating_Ui", "getRatingList",array(false,false,true)) : "<p class=\"resultS\">Aucun résultat.</p>"; 
						$html= "<h1>mes évaluations</h1><section><h1>Mes dernières évaluations</h1><div id=\"blocLastEvals\" class=\"containerBlocP\">{$resultLastEvals}</div></section><section><h1>Mes dernières meilleurs évaluations</h1><div id=\"blocTopEval\"  class=\"containerBlocP\">{$resultTopEval}</div></section><section><h1>Mes derniers morceaux non notés</h1><div id=\"blocUnrated\" class=\"containerBlocP\">{$resultUnrated}</div></section>";
						}
						break;
						
					case "mesamis":
						if (! $auth->estConnecte())
							break;
						$friendSearchForm = Recherche::searchForm("friendSearch");
						$user = $auth->getInfosAuthentification();
						$userUi = new User_Ui($user);
						
						$listeF = new Liste_Paginee("Friend_Bd", "getFriends", "WHERE id_user1={$user->getIdUser()} ORDER BY name ASC");
    					$listeFUi = new Liste_Paginee_Ui($listeF,5,7,true);
						// Gestion des bloc paginées
						if (isset($_GET['typeP']) && $_GET['typeP']=='bloc'){
							echo $listeF->count() > 0 ? $listeFUi->makeHtml("User_Ui", "getUserCard") : "<p class=\"resultS\">Vous n'avez ajouté aucun amis pour l'instant.</p>";
							echo "<script type=\"text/javascript\">addEventInteracUser();initializeVennTips();</script>";
							break; 
						} else {
							$amis = $listeF->count() > 0 ? $listeFUi->makeHtml("User_Ui", "getUserCard") : "<p class=\"resultS\">Vous n'avez ajouté aucun amis pour l'instant.</p>";
							//$amis = "";
						}
						$notificationsAskFriends = $userUi->getConcernedPageNotifications(DEMANDE_AJOUT_AMI);
						$notificationsAskFriends = $notificationsAskFriends == null ? "" : $notificationsAskFriends;
						$notificationsFriendsResponse = $userUi->getConcernedPageNotifications(DEMANDE_AJOUT_AMI_ACCEPTEE);
						$notificationsFriendsResponse = $notificationsFriendsResponse == null ? "" : $notificationsFriendsResponse;
						$html ="<h1>mes amis</h1>{$notificationsAskFriends}{$notificationsFriendsResponse}<section><h1>Rechercher parmis les utilisateurs</h1><div id=\"friendsearchform\">{$friendSearchForm}</div><div id=\"blocFriendSearchResult\" class=\"containerBlocP\"></div></section><section><h1>Mes amis</h1><div id=\"blocMyFriendS\" class=\"containerBlocP\">{$amis}</div></section><section><h1>Inviter des amis à rejoindre Miushake</h1></section>";
						$html .= "<script type=\"text/javascript\">userSearch();addEventInteracUser();addEventNotifications();initializeVennTips();</script>";
						break;
						
					case "mawatchlist":
						if (! $auth->estConnecte())
							break;
						$friendSearchForm = Recherche::searchForm("watchlistSearch");
						$user = $auth->getInfosAuthentification();
						$userUi = new User_Ui($user);
						$listeF = new Liste_Paginee("Follower_Bd", "getFollowedUsers", "id_user_subject={$user->getIdUser()} ORDER BY name ASC");
    					$listeFUi = new Liste_Paginee_Ui($listeF,5,7,true);
						// Gestion des bloc paginées
						if (isset($_GET['typeP']) && $_GET['typeP']=='bloc'){
							echo $listeF->count() > 0 ? $listeFUi->makeHtml("User_Ui", "getUserCard") : "<p class=\"resultS\">Vous ne suivez aucune personne pour l'instant.</p>";
							echo "<script type=\"text/javascript\">addEventInteracUser();initializeVennTips();</script>";
							break; 
						} else {
							$followedPeople= $listeF->count() > 0 ? $listeFUi->makeHtml("User_Ui", "getUserCard") : "<p class=\"resultS\">Vous ne suivez aucune personne pour l'instant.</p>";
							//$amis = "";
						}
						$html ="<h1>ma &laquo;watch list&raquo;</h1><section><h1>Rechercher parmis les utilisateurs</h1><div id=\"friendsearchform\">{$friendSearchForm}</div><div id=\"blocFriendSearchResult\" class=\"containerBlocP\"></div></section><section><h1>Ma watch list</h1><div id=\"blocMyWatchList\" class=\"containerBlocP\">{$followedPeople}</div></section>";
						$html .= "<script type=\"text/javascript\">userSearch();addEventInteracUser();initializeVennTips();</script>";
						break;
						
					case "mesinfos":
						if (! $auth->estConnecte())
							break;
						$user = $auth->getInfosAuthentification();
						$userUi = new User_Ui($user);
						$html = "<h1>mes informations</h1><section><h1>Mon profil</h1>{$userUi->mesInfos()}</section>";
						$html .= "<script type=\"text/javascript\">window.addEvent('domready',function(){avatarUploadInit()});</script>";
						break;
						
					case "mesnotifs":
						if (! $auth->estConnecte())
							break;
						$user = $auth->getInfosAuthentification();
						$userUi = new User_Ui($user);
						$notificationsList = "<div id=\"blocListNotifs\" class=\"containerBlocP\">".$userUi->getListNotifications()."</div>";
						if (isset($_GET['typeP']) && $_GET['typeP']=='bloc'){
							echo $userUi->getListNotifications() . "<script type=\"text/javascript\">addEventNotifications();</script>";
							break;
						}
						$html = "<h1>mes notifications</h1><section><h1>Mes dernières notifications</h1>{$notificationsList}</section>";
						$html .= "<script type=\"text/javascript\">addEventNotifications();</script>";
						break;
						
					case "artisteinfos":
						if(isset($_GET['id_title'])){
							$title = Title_Bd::getTitle($_GET['id_title']);
							$authVars = array(
									'apiKey' => LASTFM_API_KEY,
									'secret' => LASTFM_SECRET,
							);
							$lastFMApi = LastFMAPI::getInstance($authVars,"Artist");
							try {
								$infos = $lastFMApi->getArtistInfo($title->getArtist());
							} catch (Exception $e) {
								$infos = $e->getMessage();	
							}
						} else {
							$infos = "Aucune information disponible";	
						}
						$html = "<h1>a propos...</h1><section><h1>Biographie</h1>{$infos}</section>";	
						break;
						
					case "parolesinfos":
						if(isset($_GET['id_title'])){
							$title = Title_Bd::getTitle($_GET['id_title']);
							$musiXMatchApi = MusiXMatchApi::getInstance(MUSIXMATCH_API_KEY);
							try {
								$infos = $musiXMatchApi->getLyrics($title->getArtist(),$title->getName());
							} catch (Exception $e) {
								$infos = $e->getMessage();	
							}						
						} else {
							$infos = "Aucune information disponible";	
						}
						$html = "<h1>a propos...</h1><section><h1>Paroles</h1>{$infos}</section>";	
						break;
						
					case "utilisateurs":
						if (! $auth->estConnecte() || $auth->getInfosAuthentification()->getStatus() < MODO )
							break;
						$userForm = Recherche::FilterUserForm();
						$data = $_GET;
						$rechercheU = new Recherche($data,"User");
						$clauseU = $rechercheU->makeTabClause("AND id_user!={$auth->getInfosAuthentification()->getIdUser()} ORDER BY name");
						$listeU = new Liste_Paginee("User_Bd", "getUsersFromSearch", $clauseU);
						$listeUi = new Liste_Paginee_Ui($listeU,5,7,true);
						
						if (isset($_GET['typeP']) && $_GET['typeP']=='bloc' || isset($_GET['cle']) ){
							$searchUser = isset($_GET['cle']) ? $_GET['cle'] : "";
							$filtrage = strlen($searchUser) > 0 ? "<p class=\"resultS\">Résultat pour le mot clé {$searchUser} <span id=\"removeFilterUserSearch\">x</span></p>" : "";
							echo $listeU->count() > 0 ? $filtrage . $listeUi->makeHtml("User_Ui", "getUserCard",array(true)) : "<p class=\"resultS\">Aucun résultat</p>";
							echo "<script type=\"text/javascript\">addEventSetUserStatus();initializeVennTips();addEventInteracUser();</script>";
							break; 
						}
						
						$result = $listeU->count() > 0 ? $listeUi->makeHtml("User_Ui", "getUserCard",array(true)) : "<p class=\"resultS\">Aucun résultat.</p>";
						
						$html ="<h1>les utilisateurs</h1><section><h1>Liste des utilisateurs</h1><div id=\"friendsearchform\">{$userForm}</div><div id=\"blocFriendSearchResult\" class=\"containerBlocP\">{$result}</div></section>";
						$html .= "<script type=\"text/javascript\">userSearch();addEventSetUserStatus();initializeVennTips();addEventInteracUser();</script>";
						break;
						
					case "statsrecommand":
						if (! $auth->estConnecte() || $auth->getInfosAuthentification()->getStatus() < MODO )
							break;
						$stats = new Statistics();
						$html = "<h1>les statistiques</h1><section><h1>Statistiques de recommendations</h1>{$stats->getStats()}</section>";
						break;
						
					default:
						$html = "<p>Partie non implémentée</p>";
						break;	
				}
				echo $html;
			}
		
			break;
			
			
		// Raffraichit l'avatar	
		case "refreshAvatar":
			if (!$ajax || !$auth->estConnecte())
				break;
			$userUi = new User_Ui($auth->getInfosAuthentification());
			echo $userUi->getAvatarImg("vignette");
			break;
			
		// Suppr l'avatar
		case "delAvatar" :
			if (!$ajax || !$auth->estConnecte())
				break;
	 		Image_Bd::deleteUserImage($auth->getInfosAuthentification()->getIdUser());
	 		Image::supprimerRepImage($auth->getInfosAuthentification()->getIdUser());
			$userUi = new User_Ui($auth->getInfosAuthentification());
			echo $userUi->getAvatarImg("vignette");
		   break;
		   
		// Demande ajout ami
		case "addFriend" : 
			if (!$ajax || !$auth->estConnecte())
				break;
			if (!isset($_GET['id_user']) || strlen($_GET['id_user'])<1)
				throw new Exception("Erreur id_user pour la demande d'ajout d'ami");
			$userObject = User_Bd::getUser($_GET['id_user']);
			if ($userObject->getIdUser() == null)
				throw new Exception("Erreur id_user pour la demande d'ajout d'ami");
			// Si une demande opposée n'a pas été déjà faite
			$notificationOpposee =  Notification_Bd::getNotificationByRelation($userObject->getIdUser(),$auth->getInfosAuthentification()->getIdUser(),DEMANDE_AJOUT_AMI);
			if (! $notificationOpposee){
				$notification = new Notification_AddFriend(array('id_user_subject' => $auth->getInfosAuthentification()->getIdUser(), 'id_user_object' => $userObject->getIdUser()));
				$notification = Notification_Bd::addNotification($notification);
				echo "<span class=\"addFriendInteracState\">{$notification->getUserSubjectMsg()}</span><div class=\"ephemeralLightboxResponse\"><h2>Demande d'ajout d'ami</h2><p>Une demande d'ajout à vos amis a été envoyé à {$userObject->getName()}</p></div>";	 
			} else {
				// Si la personne qu'on demande comme ami nous avait déjà demandé comme amis, on l'ajoute directement	
				$notificationOpposee->setState(NOTIFICATION_DEL);
				Notification_Bd::modifyNotification($notificationOpposee);
				Friend_Bd::addFriends($auth->getInfosAuthentification()->getIdUser(),$userObject->getIdUser());
				$notification = new Notification_AcceptFriend(array('id_user_subject' => $auth->getInfosAuthentification()->getIdUser(), 'id_user_object' => $userObject->getIdUser()));
				$notification = Notification_Bd::addNotification($notification);
				echo "<span class=\"addFriendInteracState\">{$notification->getUserSubjectMsg()}</span><div class=\"ephemeralLightboxResponse\"><h2>Oppération effectuée</h2><p>Vous venez d'ajouter {$userObject->getName()} à la liste de vos amis</p></div>";	 
			}
			break;
			
		// Ajout liste d'ami
		case "addFollower":
			if (!$ajax || !$auth->estConnecte())
				break;
			if (!isset($_GET['id_user']) || strlen($_GET['id_user'])<1)
				throw new Exception("Erreur id_user pour la demande d'ajout d'ami");
			$userObject = User_Bd::getUser($_GET['id_user']);
			if ($userObject->getIdUser() == null)
				throw new Exception("Erreur id_user pour la demande d'ajout d'ami");
				
			Follower_Bd::addFollower($auth->getInfosAuthentification()->getIdUser(),$userObject->getIdUser());
			echo "<span class=\"addFollowerInteracState\">ajouté à ma watch list</span><div class=\"ephemeralLightboxResponse\"><h2>Oppération effectuée</h2><p>Vous venez d'ajouter {$userObject->getName()} à votre watch list.</p></div>";
			break;
			
		// Modification notification	
		case "modifyNotification":
			if (!$ajax || !$auth->estConnecte())
				break;
			if (!isset($_GET['id_notification']) || strlen($_GET['id_notification'])<1 || !isset($_GET['state_target']))
					throw new Exception("Erreur id_notification ou state_target");
				$notification = Notification_Bd::getNotification($_GET['id_notification']);
				$notification->setState($_GET['state_target']);
				Notification_Bd::modifyNotification($notification);
			break;
			
		// Modification droit utilisateur (modo/admin)
		case "setStatus":
			if (!isset($_GET['id_user']) || strlen($_GET['id_user'])<1 || !isset($_GET['status']))
				throw new Exception("Erreur id_user ou status");
			if ($_GET['status'] >= $auth->getInfosAuthentification()->getStatus())
				throw new Exception("Droit insuffisant");
			$user = User_Bd::getUser($_GET['id_user']);
			$user->setStatus($_GET['status']);
			User_Bd::modifyUser($user);
			$userUi = new User_Ui($user);
			echo $userUi->getModerationInteraction();
			// A continuer
			break;
			
		// Récupération des bloc sur le coté
		case "getSideBloc":
			if (!$ajax || ! isset($_GET['blocTarget']) )
				break;
			switch ($_GET['blocTarget']){
				
				case "getFriendsEvals":
					if (!$auth->estConnecte() || !isset($_GET['id_title']))
						break;
					$id_title = $_GET['id_title'];
					$user = $auth->getInfosAuthentification();
					$userUi = new User_Ui($user);						
					$listeF = new Liste_Paginee("Friend_Bd", "getFriends", "INNER JOIN Rating ON Rating.id_user=id_user2 WHERE id_user1={$user->getIdUser()} AND score>=0 AND id_title={$id_title} ORDER BY name ASC");
    				$listeFUi = new Liste_Paginee_Ui($listeF,3,7,true);
					echo $listeF->count() > 0 ? $listeFUi->makeHtml("User_Ui", "getMiniUserCardFromTitle",array($id_title)) : "<p class=\"resultS\">Aucun de vos amis n'a noté ce titre.</p>";
					echo "<script type=\"text/javascript\">addEventInteracUser();</script>";
					break;	
					
				case "getEvalByTitle":
					if (isset($_GET['id_title'])){
						echo User_Ui::getEvalByTitle($_GET['id_title']);
					}
					break;
					
				case "getLastEvals":
					if (!$auth->estConnecte())
						break;
					$user = $auth->getInfosAuthentification();
					$clauseLastEvals = "id_user={$user->getIdUser()} AND score>-1 ORDER BY time DESC LIMIT 5";
					$ratingTab = Rating_Bd::lireListe($clauseLastEvals);
					if (sizeof($ratingTab)<1){
						echo "<p>Aucune évaluations</p>";
						break;
					}
					foreach($ratingTab as $rating){
						$ratingUi = new Rating_Ui($rating);
						echo $ratingUi->getRatingList(true,true,false);
					}
					break;
					
				case "getEnBref":
					if (!$auth->estConnecte())
						break;
					$user = User_Bd::getUser($auth->getInfosAuthentification()->getIdUser());
					$userUi = new User_Ui($user);
					echo $userUi->getEnBref();
					break;
					
				case "getMusicalAffinity":
					if (!$auth->estConnecte() || !isset($_GET['id_user']))
						break;
					$user = User_Bd::getUser($_GET['id_user']);
					$userUi = new User_Ui($user);
					echo "<p>Votre affinité musicale avec {$user->getName()} sur ce que vous aimez</p>";
					echo $userUi->getVennDiagram($auth->getInfosAuthentification()->getIdUser(),JAIME,160,70);
					echo "<div class=\"clearer\"></div>";
					echo "<script type=\"text/javascript\">initializeVennTips();</script>";
					break;
					
				case "getCommonFriends":
					if (!$auth->estConnecte() || !isset($_GET['id_user']))
						break;
					$id_user = $_GET['id_user'];
					$user = $auth->getInfosAuthentification();
					$userUi = new User_Ui($user);						
					$listeF = new Liste_Paginee("Friend_Bd", "getFriends", "INNER JOIN FriendsFacebook as f2 ON f2.id_user1={$id_user} AND f1.id_user2=f2.id_user2 WHERE f1.id_user1={$user->getIdUser()} ORDER BY name ASC");
    				$listeFUi = new Liste_Paginee_Ui($listeF,3,7,true);
					echo $listeF->count() > 0 ? $listeFUi->makeHtml("User_Ui", "getMiniUserCardFriend") : "<p class=\"resultS\">Aucun amis en commun</p>";
					echo "<script type=\"text/javascript\">addEventInteracUser();</script>";
					break;
					
				default:
					break;
			}
			break;
			
			
		default:
			$titre="miushake";
			//$user = User_Bd::getUser(13);
			//$userUi = new User_Ui($user);
			//$c= $userUi->getUserStats();
			break;
 	}
 
} catch (Exception $e) {
  	$c = $e->getMessage();
  	$c .= "<pre>{$e->getTraceAsString()}</pre>";
	if ($ajax){
		echo $e->getMessage();
		echo "<pre>{$e->getTraceAsString()}</pre>";
	}
}

if ($ajax !== true){
ob_start();
  	require_once($squelette);
	$html = ob_get_contents();
	ob_end_clean();
	echo $html;
}

?>